import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    DeviceEventEmitter,
    ScrollView,
    SectionList,
    ActivityIndicator
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import Loading from "../../utils/Loading";
import Header from "../../components/header";
import { getImgUrl } from '../../utils/ComFunction'
import MerchantBaseInfo from "./components/MerchantBaseInfo";
import MerchantAuthInfo from "./components/MerchantAuthInfo";
import AsyncImage from '../../components/image/AsyncImage'
import ZhuanYinItemView from "../seekCenter/seekComponents/ZhuanYinItemView";

const isIos = Platform.OS == 'ios';

const screenW = Dimensions.get('window').width;

let navigation


export default class CompanyInfoPage extends Component {
    constructor(props) {
        super(props);
        let isFranchisee = this.props.route.params && this.props.route.params.isFranchisee ? true : false
        let isLookCarDetail = this.props.route.params && this.props.route.params.isLookCarDetail ? true : false
        this.state = {
            isLookCarDetail,
            merchantId: this.props.route.params.merchantId,
            isSelfCar: this.props.route.params.merchantId == Constant.userInfo.merchantId ? true : false,
            isFranchisee,
            selectedIndex: 0,

            isShowSortDrop: false,
            sortShowText: '排序',
            orderColumns: [],

            brand: 0,
            series: 0,

            isPriceModalVisible: false,
            markedPriceMin: 0,
            markedPriceMax: 0,

            data: {},
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            pageSize: 30,
            carSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "merchantInfo" }, //商家信息
                ]
            }, {
                'key': 'contentInfo',
                'data': []
            }],
            merchantSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "merchantInfo" }, //商家信息
                ]
            }, {
                'key': 'contentInfo',
                'data': [
                    { "cell": "merchantBaseInfo" }, //基本信息,
                    { "cell": "merchantIntroduceInfo" }, //商家介绍
                    { "cell": "merchantAuthInfo" }, //信息认证
                ]
            }],

            totalBuyerNum: 0,
            category: this.props.route.params.category || '',
            categoryArray: [],
        }
    }

    componentWillUnmount() {

    }

    componentDidMount() {
        this.getMerchantInformation()
        this.getBuyerList()
        this.getMerchantZhuanyinList()
    }

    getMerchantZhuanyinList() {
        HttpUtils.getRequest(HttpUrls.getSpecializedListByMerchantId, { merchantId: this.state.merchantId })
            .then((result) => {
                console.log('getMerchantZhuanyinList', result)
                if (result.code == 0) {
                    this.setState({
                        categoryArray: result.data,
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
            });
    }

    getMerchantInformation() {
        this.Loading.show()
        HttpUtils.getRequest(HttpUrls.getMerchantInformation, { merchantId: this.state.merchantId })
            .then((result) => {
                this.Loading.hide()
                if (result.code == 0) {
                    this.setState({
                        data: result.data,
                        selectedIndex: 0,
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} hideSepLine={true} Title={'商家详情'} ></Header>

                {
                    this.state.data ?
                        <SectionList
                            // ref={(sectionList) => { this.sectionList = sectionList }}
                            renderSectionHeader={this.renderSectionHeader}
                            stickySectionHeadersEnabled={true}
                            style={{ flex: 1 }}
                            sections={this.state.selectedIndex == 0 ? this.state.carSections : this.state.merchantSections}
                            renderItem={this.renderItem.bind(this)}
                            onEndReachedThreshold={0.1}
                            onEndReached={() => this.reachedEnd()}
                            ListFooterComponent={() => this.renderFooter()}
                            showsHorizontalScrollIndicator={false}
                            keyExtractor={this._extraUniqueKey}
                        />
                        :
                        null
                }

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }

    _extraUniqueKey(item, index) {
        return "index" + index + item;
    }

    renderItem(data) {
        if (data.item.cell == 'merchantInfo') {
            return (
                <View>
                    {this.storeInfo()}
                </View>
            )
        } else if (data.item.cell == 'merchantBaseInfo' && this.state.selectedIndex == 1) {
            return (
                <MerchantBaseInfo
                    data={this.state.data}
                />
            )
        } else if (data.item.cell == 'merchantIntroduceInfo' && this.state.selectedIndex == 1) {
            return (
                <View style={{ flexDirection: 'column', width: '100%', paddingHorizontal: 16, paddingVertical: 20, backgroundColor: '#fff', borderBlockColor: '#e4e4e4', borderBottomWidth: 0.3 }}>
                    <Text style={{ fontSize: 16, fontWeight: '500', color: '#333', marginBottom: 15 }}>商家介绍</Text>
                    <Text style={{ fontSize: 14, color: '#333', lineHeight: 18 }}>{this.state.data.merchantProfile}</Text>
                </View>
            )
        } else if (data.item.cell == 'merchantAuthInfo' && this.state.selectedIndex == 1) {
            return (
                <MerchantAuthInfo
                    storePic={this.state.data.storePic}
                    licensePic={this.state.data.licensePic}
                />
            )
        } else {
            if (this.state.selectedIndex == 0) {
                if (data.item.emptyCell) {
                    return (
                        <View style={{ width: '100%', height: 260 }}>
                            <NoData Desc="暂无数据" style={{ marginTop: gREM(40) }} />
                        </View>
                    )
                } else {
                    return (
                        <View style={{ width: '100%'}}>
                            {this.renderBuyerItem(data.item)}
                        </View>
                    )
                }
            } else {
                return (
                    null
                )
            }
        }
    }

    renderBuyerItem(item) {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                key={item.contractNo}
                onPress={() => {
                    // navigation.navigate('BuyerSetLabelPage');
                    navigation.navigate('BuyerInfoPage', {
                        buyerId: item.buyerId,
                    });
                }}>
                {/* 列表数据 */}
                <View style={styles.itemcontainer}>
                    {/* 买手相关 */}
                    <View style={styles.contractCarContainer}>
                        {item.avatar ? (
                            <Image
                                style={styles.contractcar}
                                source={{
                                    uri: getImgUrl(item.avatar),
                                }}
                            />
                        ) : (
                            <Image
                                source={require('source/image/seekCenter/default_avatar.png')}
                                style={styles.contractcar}
                            />
                        )}
                    </View>

                    <View style={styles.buyerInfoList}>
                        <View style={styles.buyerInfo}>
                            <Text style={{color: '#333', fontSize: 14}}>{item.fullname ? item.fullname : ''}</Text>
                            {/*<Text> </Text>*/}
                            {/*<Text style={{color: '#FFA500', fontSize: 13}}>*/}
                            {/*    @{item.merchantAbbreviation ? item.merchantAbbreviation : '暂无'}*/}
                            {/*</Text>*/}

                            {
                                item.nowLoginUserIsFollow == 1
                                    ?
                                    <View style={{backgroundColor: '#F5F5F5', width: 50, paddingVertical: 3, borderRadius: 3}}>
                                       <Text style={{color: '#333', fontSize: 13, textAlign: 'center'}}>已关注</Text>
                                    </View>
                                    :
                                    null
                            }

                        </View>

                        <View style={styles.buyerInfoDesc}>
                            <Text
                                numberOfLines={2}
                                ellipsizeMode="tail"
                                style={{fontSize: 14, color: '#666'}}>
                                简介: {item.preferences ? item.preferences : '暂无信息'}
                            </Text>
                        </View>
                        <View style={styles.buyerInfoTage}>
                            {/* 遍历 item.buyerTags */}
                            {item.limitShowBuyerTags?.map((tag, index) => {
                                if(tag.tagValueText == '不限'){
                                    return null;
                                }
                                return (
                                    <View style={styles.tagItem} key={index}>
                                        <Text style={styles.tagText}>
                                            {tag.tagValueText  ? tag.tagValueText : ''}
                                        </Text>
                                    </View>
                                );
                            })}
                        </View>
                    </View>
                </View>
                <View style={styles.sepLine} />
            </TouchableOpacity>
        )
    }

    renderSectionHeader = (info) => {
        let section = info.section.key;
        if (section === 'contentInfo') {
            return (
                <View style={{ flexDirection: 'column', width: '100%' }}>
                    <View style={styles.tabBox}>
                        <TouchableOpacity
                            style={styles.tabBoxItem}
                            activeOpacity={0.8}
                            onPress={() => {
                                this.setState({
                                    selectedIndex: 0,
                                })
                            }}
                        >
                            <Text style={this.state.selectedIndex == 0 ? styles.tabTitleTextSel : styles.tabTitleText}>{(this.state.totalBuyerNum != 0 ? this.state.totalBuyerNum + ' ' : '0') + '个买手'}</Text>
                            <View style={this.state.selectedIndex == 0 ? styles.tabIndexSelBox : styles.tabIndexBox} />
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={styles.tabBoxItem}
                            activeOpacity={0.8}
                            onPress={() => {
                                this.setState({
                                    selectedIndex: 1,
                                })
                            }}
                        >
                            <Text style={this.state.selectedIndex == 1 ? styles.tabTitleTextSel : styles.tabTitleText}>{'商家信息'}</Text>
                            <View style={this.state.selectedIndex == 1 ? styles.tabIndexSelBox : styles.tabIndexBox} />
                        </TouchableOpacity>
                    </View>
                </View>

            )
        }
    }

    renderFooter() {
        if (this.state.carSections[1].data.length == 0) {
            return (
                null
            )
        }
        if (this.state.selectedIndex == 1) {
            return (
                <View style={{ height: Constant.bottomHeight }} />
            );
        }

        if (this.state.showFoot == 2) {
            return (
                <View style={{ padding: 10, backgroundColor: '#ffffff', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                    <ActivityIndicator size="small" color="#333333" />
                    <Text style={{ marginLeft: 10, fontSize: 15, color: '#333333' }}>加载中...</Text>
                </View>
            )
        } else {
            return (
                <View style={{ height: Constant.bottomHeight }} />
            )
        }
    }

    reachedEnd() {
        if (this.state.selectedIndex == 0 && this.state.carSections[1].data.length == 0) {
            return null;
        }

        if (this.state.showFoot != 0) {
            return null;
        }
        let pageNo = this.state.pageNo + 1
        this.setState({
            showFoot: 2,
            pageNo: pageNo
        }, function () {
            this.getBuyerList()
        });

    }

    refreshBuyerList() {
        this.setState({
            pageNo: 1,
            carSections: [{
                'key': 'baseInfo',
                'data': [
                    { "cell": "merchantInfo" }, //商家信息
                ]
            }, {
                'key': 'contentInfo',
                'data': []
            }]
        }, function () {
            this.getBuyerList()
        })
    }

    getBuyerList() {
        let params = {
            merchantId: this.state.merchantId,
            // orderColumns: [{ "orderAsc": false, "column": "purchaseDate" }],
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
        }
        // 是否查询已关注
        params['optionShowFollow'] = 1

        HttpUtils.postRequest(HttpUrls.queryBuyerList, params)
            .then((result) => {

                if (result.data) {
                    this.setState({
                        totalBuyerNum: result.data.totalSize
                    })
                }
                if (result.data && result.data.resultList.length > 0) {
                    let carsList = this.state.carSections[1].data
                    carsList = carsList.concat(result.data.resultList)
                    this.setState({
                        carSections: [{
                            'key': 'baseInfo',
                            'data': [
                                { "cell": "merchantInfo" }, //商家信息
                            ]
                        }, {
                            'key': 'contentInfo',
                            'data': carsList
                        }]
                    })
                    if (result.data.resultList.length < this.state.pageSize) {
                        this.setState({
                            showFoot: 1
                        });
                    } else {
                        this.setState({
                            showFoot: 0
                        });
                    }
                } else {
                    if (this.state.pageNo == 1) {
                        this.setState({
                            carSections: [{
                                'key': 'baseInfo',
                                'data': [
                                    { "cell": "merchantInfo" }, //商家信息
                                ]
                            }, {
                                'key': 'contentInfo',
                                'data': [
                                    { 'emptyCell': true }
                                ]
                            }]
                        })
                    }
                    this.setState({
                        showFoot: 1
                    });
                }
            })
            .catch((error) => {

            });
    }

    storeInfo() {
        return (
            <ZhuanYinItemView
                item={this.state.data}
                isShowBuyNum={false}
                title={this.state.data.merchantAbbreviation ? this.state.data.merchantAbbreviation : (this.state.data.merchantName ? this.state.data.merchantName : '暂未填写商家名称')}
                image={this.state.data.merchantLogoPic}
                authenCode={this.state.data.authenCode}
                address={(this.state.data.provinceName ? this.state.data.provinceName : '') + (this.state.data.cityName ? this.state.data.cityName : '') + (this.state.data.districtName ? this.state.data.districtName : '') + (this.state.data.address ? this.state.data.address : '')}
                category={this.state.category}
                categoryArray={this.state.categoryArray}
            ></ZhuanYinItemView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    depositImg: {
        marginTop: 12,
        marginLeft: 12,
        width: 40,
        height: 15,
        position: 'absolute',
        zIndex: 100,
    },
    merchantInfo: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
        marginLeft: 15,
    },

    tabBox: {
        width: '100%',
        height: 40,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 16,
        backgroundColor: '#FFF',
        borderTopColor: '#e4e4e4',
        borderTopWidth: 0.3
    },
    tabBoxItem: {
        flex: 1,
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabTitleTextSel: {
        color: '#333',
        fontSize: 14,
        fontWeight: '500'
    },
    tabTitleText: {
        color: '#999',
        fontSize: 14,
    },
    tabIndexBox: {
        width: 26,
        height: 3,
        backgroundColor: '#fff'
    },
    tabIndexSelBox: {
        position: 'absolute',
        bottom: 0,
        width: 26,
        height: 3,
        backgroundColor: '#FFE000'
    },

    // 买手列表
    itemcontainer: {
        backgroundColor: '#FFFFFF',
        flexDirection: 'row',
        paddingHorizontal: 15,
        paddingVertical: 15,
    },
    contractCarContainer: {
        borderRadius: 8,
        flexDirection: 'row',
    },
    contractcar: {
        width: 87,
        height: 121,
        borderRadius: 6,
        // marginRight: 15
    },
    buyerInfoList: {
        marginHorizontal: 12,
        width: '67%',
        // backgroundColor: '#c5c5c5',
        overflow: 'hidden'
    },
    buyerInfo: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    buyerInfoDesc: {
        marginTop: 5,
    },
    buyerInfoTage: {
        flexWrap: 'wrap',
        flexDirection: 'row',
        marginTop: 10,
    },
    tagItem: {
        backgroundColor: '#fff399', // 背景色
        borderRadius: 4, // 圆角
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8, // 标签之间的间距
        marginTop: 5,
    },
    tagText: {
        fontSize: 11, // 字体大小
        color: '#333333', // 文字颜色
    },

    sepLine: {
        position: 'absolute',
        bottom: 0,
        // left: 15,
        width: screenW - 15,
        height: 0.5,
        backgroundColor: '#e4e4e4',
    },


})